<template>
  <div class='home'>
    <!--顶部-->
    <div class="header">
      <div class="store" @click="toSelectStore">
        <div class="store-left">
          <img v-if="shop_detail.thumb_url" :src="shop_detail.thumb_url" />
        </div>
        <div class="store-right">
          <span>{{shop_detail.name}}</span>
          <img class="icon" v-if="FileUrl.length>0" :src="FileUrl+'down-icon.png'">
        </div>
      </div>
      <div class="search">
        <div class="search-btn" @click="toSearch">
          <icon type="search" size="16"></icon>
          搜索
        </div>
      </div>
    </div>
    <!--end-->

    <!-- banner -->
    <swiper autoplay indicator-dots='true' circular="true" indicator-color="rgba(0, 0, 0, .3)" indicator-active-color="white">
      <swiper-item v-for="(value,index) in imgList" :key="index" @click="toAdvert(value.link_url)">
        <img :src="value.img_url" class="slide-image" lazy-load="true"/>
      </swiper-item>
    </swiper>
    <!-- banner结束 -->

    <!--拼团动态-->
    <div class="assemble" v-if="myGroupList!=null">
      <div class="assemble-title">拼团动态</div>
      <div class="assemble-item" v-for="(item,index) in myGroupList" :key="index" @click="toAssembleDetail(item)">
        <div class="assemble-body">
          <div class="assemble-img">
            <img :src="item.activity_group_info.goods_info.thumb_url" mode="aspectFit"/>
            <span class="num">{{item.activity_group_info.max_group_num}}人团</span>
          </div>
          <div class="assemble-content">
            <div class="title">{{item.activity_group_info.goods_info.name}}</div>
            <div class="mode">
              <img class="mode-icon" v-if="FileUrl.length>0" :src="FileUrl+'store-icon.png'" />
              <span>到店自提</span>
            </div>
            <div class="price-btn">
              <span>￥{{item.activity_group_info.goods_info.s_price}}</span>
              <span class="original">￥{{item.activity_group_info.goods_info.m_price}}</span>
              <button class="blue-btn">邀请</button>
            </div>
          </div>
        </div>
        <div class="assemble-time">{{discountTimerGroup[index].lastHour}}时{{discountTimerGroup[index].lastMin}}分{{discountTimerGroup[index].lastSecond}}秒</div>
      </div>
    </div>
    <!--拼团动态end-->

    <!--超值拼团-->
    <div class="assemble" v-if="groupList.length>0">
      <div class="assemble-title">超值拼团
<!--        <span class="rule" @click="toRule('assemble')">规则</span>-->
      </div>
      <div class="assemble-item" v-for="(item, index) in groupList" :key="index" @click="toGoodsAssemble(item)">
        <div class="assemble-body">
          <div class="assemble-img">
            <img :src="item.goods_info.thumb_url" mode="aspectFit"/>
            <span class="num">{{item.max_group_num}}人团</span>
          </div>
          <div class="assemble-content">
            <div class="title">{{item.goods_info.name}}</div>
            <div class="mode">
              <img class="mode-icon" v-if="FileUrl.length>0" :src="FileUrl+'store-icon.png'" />
              <span>到店自提</span>
            </div>
            <div class="price-btn">
              <span>￥{{item.goods_info.s_price}}</span>
              <span class="original">￥{{item.goods_info.m_price}}</span>
              <button class="blue-btn">去拼团</button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--超值拼团end-->

    <!--推荐-->
    <div class="recommend" v-if="recommendData.length>0">
      <div class="recommend-title">推荐</div>
      <div class="recommend-list">
        <div class="recommend-item" v-for="(item,index) in recommendData" :key="index"  @click="toGoodsDetail(item.id)">
          <div class="item-img">
            <img :src="item.thumb_Url" mode="aspectFill"/>
          </div>
          <div class="item-des">{{item.name}}</div>
          <div class="price">
            <span>￥{{item.s_price}}</span>
            <span class="original">￥{{item.m_price}}</span>
          </div>
          <div class="shopList_item_icon" @click.stop="addCart(item)">
            <img src="../../../static/images/goodsDetails/icon_car.png" />
          </div>
          <div class="shopList_item_num" v-if="item.total_goods_num>0">{{item.total_goods_num}}</div>
        </div>
      </div>
    </div>
    <!--推荐end-->
  </div>
</template>

<script>

  export default {
    data() {
      return {
        FileUrl: this.$base,
        recommendData: [],
        imgList:[],
        groupList:[],
        myGroupList: [],
        discountTimerGroup: '',
        countTimerGroup:[],//用于清除倒计时
        countTimer:'',
        latitude: 23,
        longitude: 113,
        storeList:[],
        min_distance: 0,
        shop_detail: '',
        shop_id:'',
        page: 1
      }
    },
    //下拉触底
    onReachBottom() {
      this.page++;
      this.getGoodList()
      // this.getDiscount()
    },
    //上拉
    onPullDownRefresh() {
      this.page = 1;
      this.clearAllInterval()
      // this.getDiscount();
      this.getUserGroupStatus();
      this.getBanner();
      this.getGoodList();
      this.getActivityGroupList();
      // this.newData = []
      // this.recommendData = []
      // this.discountData = []
      // Do something when pull down.
    },
    //分享
    onShareAppMessage() {
      return {
        title: '波罗蛋在线商城',
        desc: '',
      }
    },
    onLoad(query){
      // if (query.shop_id){
      //   this.shop_id = query.shop_id;
      //   this.getShopDetail();
      // }
      this.getGoodList();
      this.getUserGroupStatus();
      this.getBanner();
      // this.getGoodList();
      this.getActivityGroupList();


    },
    onShow() {
      if (wx.getStorageSync('shop_id')) {
        this.shop_id = wx.getStorageSync('shop_id');
        this.getShopDetail();
      }else {
        this.wxCHaeee();
      }
      this.getUserGroupStatus();
      this.getBanner();
      // this.getGoodList();
      this.getActivityGroupList();
      // this.page = 0
      this.clearAllInterval()
      // this.getDiscount();
      if (wx.getStorageSync('toPage')){
        wx.removeStorageSync('toPage')
      }

    },
    onHide() {
      // this.discountData=[]
      // this.discountData = []
      this.clearAllInterval()

    },
    methods: {
      wxCHaeee(){
        wx.getSetting({
          success: (res) => {
            console.log(JSON.stringify(res))
            let _this = this;
            if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
              wx.showModal({
                title: '请求授权当前位置',
                content: '需要获取您的地理位置，请确认授权',
                success: function (res) {
                  if (res.cancel) {
                    wx.showToast({
                      title: '拒绝授权',
                      icon: 'none',
                      duration: 1000
                    })
                    _this.getShopList();

                  } else if (res.confirm) {
                    wx.openSetting({
                      success: function (dataAu) {
                        if (dataAu.authSetting["scope.userLocation"] == true) {
                          wx.showToast({
                            title: '授权成功',
                            icon: 'success',
                            duration: 1000
                          })
                          //再次授权，调用wx.getLocation的API
                          wx.getLocation({
                            type: 'wgs84',
                            success (res) {
                              _this.latitude = res.latitude;
                              _this.longitude = res.longitude;
                              if (_this.shop_id==''){
                                _this.getShopList();
                              }
                            }
                          })
                        } else {
                          wx.showToast({
                            title: '授权失败',
                            icon: 'none',
                            duration: 1000
                          })
                        }
                      }
                    })
                  }
                }
              })
            } else if (res.authSetting['scope.userLocation']) {
              wx.getLocation({
                type: 'wgs84',
                success (res) {
                  _this.latitude = res.latitude;
                  _this.longitude = res.longitude;
                  if (_this.shop_id==''){
                    _this.getShopList();
                  }
                }
              })
            }
            else {
              _this.getShopList();
            }
          }
        })
      },
      //跳转规则
      toRule(type){
        wx.navigateTo({url: '/pages/rule/main?type='+type})
      },
      async addCart(item){//添加到购物车
        const _this=this
        var userToken=wx.getStorageSync('userToken')
        let res=await this.$request.postData('/goods/addShopCart',{goods_id:item.id,num:1,user_token:userToken,goods_spu_id:item.default_goods_spu_id,shop_id:wx.getStorageSync('shop_id')||''})
        wx.showLoading()
        if(res.data.level=='success'){
          this.$currency.showToast('成功加入购物车','success',1500);
          // this.showModal=false;
          wx.hideLoading();
          _this.cart_num = parseInt(res.data.total_goods_num);
          _this.page = 1;
          _this.getGoodList()

        }else{
          wx.hideLoading({success:function(){
              _this.$currency.showToast(res.data.message,'none',1500)
            }});

        }
      },
      //获取推荐列表
      async getGoodList() {
        wx.showLoading()
        let res = await this.$request.getData('/goods/getRecommendGoodsList', {page: this.page, limit: 10,user_token: wx.getStorageSync('userToken') , shop_id:wx.getStorageSync('shop_id')||''})
        if (res.data.level == 'success') {
          // this.goodsListName = res.data.data
          if (this.page==1){
            this.recommendData = res.data.data;
          } else {
            if (res.data.data.length>0){
              this.recommendData = this.recommendData.concat(res.data.data)
            } else {
              this.page--;
            }

          }
          // res.data.data.forEach((item) => {
          //   if (item.is_recommend == '1') {
          //     this.recommendData.push(item)
          //   }
          // })
          wx.hideLoading()
        }
      },
      //获取门店列表
      async getShopList(){
        let params = {
          page: 1,
          limit: 99999
        }
        const res = await this.$request.getData('/other/getShopList',params);
        if (res.data.level == 'success'){
          this.storeList = res.data.data;
          this.totalPage = res.data.page_info.total;
          await this.forList();
          console.log(this.shop_id)
          this.getShopDetail();
        }
      },
      forList(){
        for (let i=0;i<this.storeList.length; i++){
          this.storeList[i].distance = this.getDistance(this.storeList[i].lat,this.storeList[i].lng);
          if (i>0){
            this.storeList[i].distance = this.storeList[i].distance.toFixed(0)
            if (parseInt(this.storeList[i].distance) < parseInt(this.min_distance)){
              this.min_distance = this.storeList[i].distance;
              this.shop_id = this.storeList[i].id
            }
          } else {
            this.storeList[i].distance = this.storeList[i].distance.toFixed(0)
            this.min_distance = this.storeList[i].distance;
            this.shop_id = this.storeList[i].id
          }
          if (this.storeList[i].distance>1000) {
            this.storeList[i].distance_desc = (this.storeList[i].distance/1000).toFixed(2) + "km";
          }else {
            this.storeList[i].distance_desc = this.storeList[i].distance.toFixed(2) + "m";
          }
        }
        console.log('aa')
      },
      getDistance(lat,lng){
        lat = lat || 0;
        lng = lng || 0;
        this.latitude = this.latitude || 0;
        this.longitude = this.longitude || 0;
        var rad1 = lat * Math.PI / 180.0;
        var rad2 = this.latitude * Math.PI / 180.0;
        var a = rad1 - rad2;
        var b = lng * Math.PI / 180.0 - this.longitude * Math.PI / 180.0;
        var r = 6378137;
        return r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)))
      },
      //获取店铺详情
      async getShopDetail(){
        const res = await this.$request.getData('/other/getShopDetail',{id:this.shop_id});
        if (res.data.level == 'success'){
          this.shop_detail = res.data.data;
          wx.setStorageSync('shop_id',this.shop_id)
        }
      },
      //获取轮播图
      async getBanner() {
        let res = await this.$request.getData('/other/getBannerList');
        if (res.data.level == 'success') {
          this.imgList = res.data.data;
          wx.stopPullDownRefresh()
        }
      },
      //获取我参与的拼团
      async getUserGroupStatus(){
        let res = await this.$request.getData('/activity/getUserGroupStatus',{user_token: wx.getStorageSync('userToken')})
        if (res.data.level == 'success'){
          this.myGroupList = res.data.data;
          this.discountTimerGroup= this.myGroupList.map(item=>{
            return {'timer':item.end_time}
          })
          this.discountTimerGroup.forEach((item,index)=>{
            this.countTimeGroup(item,index)
          })
        }
      },
      //获取拼团活动列表接口
      async getActivityGroupList(){
        let res = await this.$request.getData('/activity/getActivityGroupList');
        if (res.data.level == 'success'){
          this.groupList = res.data.data
        }
      },
      toAssembleDetail(item){
        this.$currency.navigateTo(`/pages/assembleDetail/main?order_num=${item.order_num}`)
      },
      toGoodsAssemble(item){
        this.$currency.navigateTo(`/pages/goodsAssemble/main?id=${item.goods_id}&activeId=${item.id}`)
      },
      toSearch(){
        wx.navigateTo({url: '/pages/search/main'})
      },
      toSelectStore(){
        wx.navigateTo({url: '/pages/stores/main?lat='+this.latitude+'&lng='+this.longitude})
      },
      toGoodsDetail(id) {
        wx.navigateTo({url: '/pages/goodsDetail/main?id=' + id})
      },
      toAdvert(url) {
        let pattern = /^\/pages/
        if (pattern.exec(url)) {
          this.$currency.navigateTo(url)
        } else {
          wx.navigateTo({url: '/pages/advert/main?url=' + url})
        }
      },
      toDiscountDetail(item) {
        wx.navigateTo({url: `/pages/discount/goodsDiscount/main?id=${item.goods_id}&activeId=${item.id}`})
        console.log(`/pages/discount/goodsDiscount/main?id=${item.goods_id}&activeId=${item.id}`)
      },
      countTimeGroup(item,index) {//数组倒计时
        var that = this;

        const timer=setInterval(()=>{
          var date = new Date();
          var now = date.getTime();
          var endDate = new Date(item.timer);//设置截止时间
          if(isNaN(endDate)){
            // iso不能识别2018-08-30格式时间
            var timer1=item.timer.replace(/-/g, '/');
            var endDate=new Date(timer1)
          }
          var end = endDate.getTime();
          var leftTime = end - now; //时间差
          var d, h, m, s, ms;
          //  if(leftTime>=86400){//小于1小时才显示倒计时
          //     that.$set(this.discountTimerGroup,index,{...this.discountTimerGroup[index],showLimitData:true})
          //   }
          if (leftTime >= 0) {
            d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
            h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
            m = Math.floor(leftTime / 1000 / 60 % 60);
            s = Math.floor(leftTime / 1000 % 60);
            // ms = Math.floor(leftTime % 1000);
            // ms = ms < 100 ? "0" + ms : ms
            s = s < 10 ? "0" + s : s
            m = m < 10 ? "0" + m : m
            h = h < 10 ? "0" + h : h

            // this.countdown=d + "：" + h + "：" + m + "：" + s + ":" + ms;
            // console.log(d + "：" + h + "：" + m + "：" + s + ":" + ms)

            if(leftTime>=86400){//小于1小时才显示倒计时
              that.$set(this.discountTimerGroup,index,{...this.discountTimerGroup[index],lastDay:d,lastHour:h,lastMin:m,lastSecond:s,state:'showLimit'})
            }else{
              that.$set(this.discountTimerGroup,index,{...this.discountTimerGroup[index],lastDay:d,lastHour:h,lastMin:m,lastSecond:s,state:'hideLimit'})
            }


          } else {
            that.$set(this.discountTimerGroup,index,{...this.discountTimerGroup[index],lastDay:d,lastHour:h,lastMin:m,lastSecond:s,state:'timeOut'})//显示活动结束
            console.log('已截止')
          }
        },1000)
        this.countTimerGroup.push(timer)
      },
      clearAllInterval(){//清除所有定时器
        this.countTimerGroup.forEach(item=>{
          if(item){
            clearInterval(item)
          }
        })
      },
    },
  }
</script>

<style scoped lang="scss">
  @import "../../common/css/mixin";
  .home {
    width: 100%;
    padding-top: 170rpx;
    /*background: #eee;*/
  }
  .header{
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 170rpx;
    background: #ffffff;
    z-index: 3000;
    box-shadow: 0rpx 2rpx 10rpx 4rpx #b0b0b0;
    .store{
      @include flex(flex-start);
      flex-direction: row;
      height: 60rpx;
      padding: 10rpx 20rpx;
      width: calc(100vw - 40rpx);
      .store-left{
        width: 60rpx;
        height: 60rpx;
        border-radius: 360rpx;
        overflow: hidden;
        margin-right: 10rpx;
      }
      .store-right{
        @include flex(flex-start);
        flex-direction: row;
        width: calc(100% - 70rpx);
        span{
          display: block;
          height: 60rpx;
          line-height: 60rpx;
          font-weight: bold;
          font-size: 16px;
          margin-right: 20rpx;
          max-width: 50%;
          @include ellipsis(1)
        }
        .icon{
          width: 40rpx;
          height: 40rpx;
        }
      }
    }
    .search{
      width: calc(100vw - 40rpx);
      height: 60rpx;
      padding: 10rpx 20rpx 20rpx 20rpx;
      .search-btn{
        width: 100%;
        text-align: center;
        height: 60rpx;
        line-height: 60rpx;
        border-radius: 360rpx;
        border: 1rpx solid #dadada;
        color: #666666;
        @include flex();
        flex-direction: row;
        icon{
          width: 32rpx;
          height: 32rpx;
          margin: 0 20rpx;
        }
      }
    }
  }
  swiper{
    width: 100vw;
    height: 50vw;
  }
  .assemble{
    background: #ffffff;
    margin-top: 20rpx;
    .assemble-title{
      padding: 0 20rpx;
      height: 80rpx;
      line-height: 80rpx;
      font-size: 32rpx;
      font-weight: bold;
      .rule{
        float: right;
        font-size: 24rpx;
        color: #1a8acf;
        font-weight: normal;
      }
    }
    .assemble-item{
      padding: 30rpx 20rpx;
      border-bottom: 1rpx solid #ebebeb;
      .assemble-body{
        @include flex(flex-start);
        flex-direction: row;
        height: 180rpx;
        .assemble-img{
          position: relative;
          width: 320rpx;
          height: 180rpx;
          img{
            max-width: 100%;
            max-height: 100%;
          }
          .num{
            position: absolute;
            top:0;
            left: 0;
            padding: 8rpx;
            font-size: 20rpx;
            background: #cbcbcb;
            border-radius: 24rpx;
          }
        }
        .assemble-content{
          width: calc(100% - 340rpx);
          height: 180rpx;
          margin-left: auto;
          @include flex(flex-start,flex-start);
          flex-direction: column;
          .title{
            line-height: 50rpx;
            height: 50rpx;
            width: 100%;
            @include ellipsis(1)
          }
          .mode{
            font-size: 26rpx;
            @include flex(flex-start);
            flex-direction: row;
            height: 80rpx;
            .mode-icon{
              width: 30rpx;
              height: 30rpx;
              margin-right: 10rpx;
            }
          }
          .price-btn{
            font-size: 26rpx;
            @include flex(flex-start,flex-end);
            flex-direction: row;
            height: 50rpx;
            width: 100%;
            .original{
              font-size: 22rpx;
              color: #707070;
              text-decoration: line-through;
              padding-left: 20rpx;
            }
            .blue-btn{
              margin-right: 0;
              margin-left: auto;
              background: red;
              color: #ffffff;
              padding: 0 30rpx;
              font-size: 30rpx;
              height: 50rpx;
              line-height: 50rpx;
            }
          }
        }
      }
      .assemble-time{
        padding-top: 10rpx;
        font-size: 24rpx;
        color: #e12317;
      }
    }
    .assemble-item:last-child{
      border: none;
    }
  }
  .recommend{
    background: #ffffff;
    margin-top: 20rpx;
    .recommend-title{
      height: 80rpx;
      line-height: 80rpx;
      font-weight: bold;
      font-size: 32rpx;
      width: calc(100vw - 40rpx);
      background: #ffffff;
      padding: 0 20rpx;
    }
    .recommend-list{
      @include flexWrap(flex-start,flex-start);
      flex-direction: row;
      width: 100vw;
      /*background: #ffffff;*/
      .recommend-item{
        width: 47%;
        /*padding: 20rpx;*/
        margin-left: 15rpx;
        margin-bottom: 30rpx;
        /*border-radius: 16rpx;*/
        overflow: hidden;
        background: #ffffff;
        position: relative;
        border: 1px solid #e2e2e2;
        @include flex();
        flex-direction: column;
        .item-img{
          width: 100%;
          height: 352.5rpx;
        }
        .item-des{
          height: 80rpx;
          line-height: 80rpx;
          width: 95%;
          @include ellipsis(1);
        }
        .price{
          font-size: 26rpx;
          @include flex(center,flex-start);
          flex-direction: column;
          height: 60rpx;
          width: 95%;
          color: #e12317;
          .original{
            font-size: 22rpx;
            color: #707070;
            text-decoration: line-through
          }
        }
        .shopList_item_icon{
          position: absolute;
          bottom: 20rpx;
          right: 20rpx;
          width: 50rpx;
          height: 50rpx;
        }
        .shopList_item_num{
          position: absolute;
          bottom: 50rpx;
          right: 20rpx;
          width: 25rpx;
          height: 25rpx;
          font-size: 20rpx;
          background: #e12317;
          border-radius: 360rpx;
          color: #ffffff;
          text-align: center;
          line-height: 25rpx;
        }
      }
      .recommend-item:nth-child(even){
        margin-right: 0;
      }
    }
  }
</style>
